<template>
  <div>
    <el-card>
      <div slot="header">
        <span>{{typeName}}用户</span>
      </div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" label-position="left">
        <el-form-item label="姓名:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请填写"></el-input>
        </el-form-item>
        <el-form-item label="归属机构:" prop="officeId" :rules="{required: true, message: '请选择归属机构'}">
          <el-cascader
            expand-trigger="hover"
            :props="officeProps"
            :options="officeData"
            v-model="officeValue"
            change-on-select
            @change="handleChange"
            placeholder="请选择">
          </el-cascader>
        </el-form-item>
        <el-form-item label="用户编号:" prop="no">
          <el-input v-model="ruleForm.no" placeholder="请填写"></el-input>
        </el-form-item>
        <el-form-item label="身份证号码:" prop="idcard">
          <el-input v-model="ruleForm.idcard" placeholder="请填写"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="ruleForm.mobile" placeholder="请填写"></el-input>
        </el-form-item>
        <el-form-item label="角色:" prop="roleId">
          <el-select v-model="ruleForm.roleId" placeholder="请选择" @change="selectChange">
            <el-option v-for="item in selectData" :value="item.id" :label="item.name" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="分组权限：" prop="groupId" :rules="{required: true, message: '请选择设备分组'}">
          <el-col :md="4">
            <el-cascader
              expand-trigger="hover"
              :show-all-levels="false"
              :props="equipProps"
              :options="equipData"
              v-model="ruleForm.groupId"
              @change="handleChangeEqu"
              placeholder="请选择">
            </el-cascader>
          </el-col>
        </el-form-item>-->
        <el-form-item label="登录名:" prop="loginName">
          <el-input v-model="ruleForm.loginName" placeholder="请填写"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="ruleForm.password" placeholder="请填写"></el-input>
        </el-form-item>
        <el-form-item label="确认密码:" prop="confirmPwd">
          <el-input v-model="ruleForm.confirmPwd" placeholder="请填写"></el-input>
        </el-form-item>
        <el-form-item label="地址信息:" prop="address">
          <el-input v-model="ruleForm.address" placeholder="请填写"></el-input>
        </el-form-item>
        <el-form-item label-width="0">
          <el-button class="white-btn" size="small" @click="onCancel">取消</el-button>
          <el-button class="green-btn" size="small" @click="submitForm('ruleForm')">确定</el-button>
          <span>（<span style="color: red;">* </span>为必填项）</span>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addUser, updateUser, getUserDetail, getSysRoleList, createSysAccount } from '@/api/sysSettings/user'
import {getSysOfficeTree} from '@/api/sysSettings/company'
import { Message } from 'element-ui'
/*import { getEuipGroup } from '@/api/equipManagement/equipmentInformation'*/
export default {
  name: 'info',
  data () {
    // 校验手机号码
    let isPoneAvailable = (phone) => {
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (reg.test(phone)) {
        return true
      } else {
        return false
      }
    }
    // 校验身份证号码
    let isCardNoAvailabel = (cardno) => {
      let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (reg.test(cardno)) {
        return true
      } else {
        return false
      }
    }
    return {
      id: this.$route.params.id, // 路由参数--id
      type: this.$route.params.type, // 路由参数--type
      typeName: '', // 路由名称
      // 表单数据
      ruleForm: {
        name: '', // 姓名
        officeId: '', // 归属机构
        no: '', // 用户编号
        idcard: '', // 身份证编号
        loginName: '',
        password: '', // 密码
        confirmPwd: '', // 确认密码
        mobile: '', // 联系电话
        address: '', // 地址
        roleId: '' // 角色
      },
      // 表单验证规则
      rules: {
        name: [{required: true, message: '请填写姓名', trigger: 'blur'}],
        loginName: [{required: true, message: '请填写登录账号', trigger: 'blur'}],
        no: [{required: true, message: '请填写用户编号', trigger: 'blur'}],
        idcard: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === '') {
                return callback(new Error('请填写身份证号码'))
              } else if (!isCardNoAvailabel(value)) {
                return callback(new Error('身份证号不合法,请重新填写'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === '') {
                return callback(new Error('请填写手机号'))
              } else if (!isPoneAvailable(value)) {
                return callback(new Error('手机号不合法,请重新填写'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              if (this.ruleForm.confirmPwd !== '') {
                if (value !== this.ruleForm.confirmPwd) {
                  return callback(new Error('两次填写的密码不一致'))
                } else {
                  this.$refs['ruleForm'].clearValidate('confirmPwd')
                  callback()
                }
              } else {
                this.$refs['ruleForm'].clearValidate('confirmPwd')
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        confirmPwd: [
          {
            validator: (rule, value, callback) => {
              if (value !== this.ruleForm.password) {
                return callback(new Error('两次填写的密码不一致'))
              } else {
                this.$refs['ruleForm'].clearValidate('password')
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        roleId: [{required: true, message: '请选择角色', trigger: 'change'}]
      },
      // 级联选择器配置项
      officeProps: {
        value: 'id',
        label: 'name',
        children: 'childList'
      },
      equipProps: {
        multiple: true,
        value: 'id',
        label: 'name',
        children: 'groupings'
      },
      officeData: [], // 归属机构数据
      officeValue: [], // 归属机构默认值
      selectData: [], // 角色选择框数据
      equipData: []
    }
  },
  mounted () {
    if (this.type === 'add') {
      this.typeName = '新增'
    } else if (this.type === 'update') {
      this.typeName = '修改'
      this.getUserInfo(this.id)
    }
    this.getOfficeTree()
    this.getRoleList()
  },
  methods: {
    // 获取用户信息
    getUserInfo (id) {
      let param = {
        id: id
      }
      getUserDetail(param).then(response => {
        let data = response.object
        this.officeValue = data.officeIdList || []
        this.ruleForm = {
          id: this.id,
          name: data.name,
          roleId: data.roleId,
          idcard: data.idcard,
          officeId: data.officeId,
          no: data.no,
          loginName: data.loginName,
          mobile: data.mobile,
          address: ''
        }
      })
    },
    // 获取机构树
    getOfficeTree () {
      let param = {}
      getSysOfficeTree(param).then(response => {
        let data = response.object.list
        this.officeData = this.handleResponseValue(data)
      })
    },
    // 处理返回值数组中为空的属性
    handleResponseValue (array) {
      array.forEach(item => {
        if (item.childList && item.childList.length > 0) {
          this.handleResponseValue(item.childList)
        } else {
          delete item.childList
        }
      })
      return array
    },
    // 获取角色列表
    getRoleList () {
      let param = {
        'pageNo': 1,
        'pageSize': 999,
        'name': '',
        'officeId': '',
        'isSys': 0
      }
      getSysRoleList(param).then(response => {
        let data = response.object
        this.selectData = data.list
      })
    },
    // 选择归属机构
    handleChange (val) {
      this.ruleForm.officeId = val[val.length - 1]
    },
    // 获取分组列表
    /*getGroupList () {
      let param = {
        isAll: 1
      }
      getEuipGroup(param).then(response => {
        let data = response.object
        this.equipData = data
        console.log(data)
      }).catch(error => {
        Message({
          message: error.message,
          type: 'error'
        })
      })
    },*/
    //
   /* handleChangeEqu (val) {
      console.log(val)
      this.ruleForm.groupId = val
    },*/
    // 下拉选择框选择事件
    selectChange (val) {
      this.ruleForm.roleId = val
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗?', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: ''
          }).then(() => {
            if (this.type === 'add') {
              addUser(this.ruleForm).then(response => {
                this.$router.push('/system/user')
              })
              // 添加账户接口参数
              // let accountParam = {
              //   'userName': this.ruleForm.name,
              //   'idNumber': this.ruleForm.no,
              //   'telephone': this.ruleForm.mobile,
              //   'balance': 0,
              //   'officeId': this.ruleForm.officeId,
              //   'officeName': '',
              //   'userAddr': this.ruleForm.address,
              //   'cardNo': this.ruleForm.no,
              //   'cardType': 0,
              //   'cardStatus': 0,
              //   'bindingStatus': 0,
              //   'userNo': '',
              //   'remark': ''
              // }
              // createSysAccount(accountParam).then()
            } else if (this.type === 'update') {
              updateUser(this.ruleForm).then(response => {
                this.$router.push('/system/user')
              })
            }
          }).catch(() => {})
        } else {
          Message({
            message: '提交失败',
            type: 'error'
          })
          return false
        }
      })
    },
    // 取消按钮
    onCancel () {
      this.$router.push('/system/user')
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-input, .el-cascader, .el-select, .el-switch { width: 300px; }
  @import 'src/styles/settings.scss';
</style>
